package com.cheejee.goodscenter.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cheejee.goodscenter.dao.BrandPropertiesGroupMapper;
import com.cheejee.goodscenter.dao.BrandPropertiesTemplateMapper;
import com.cheejee.goodscenter.module.entity.BrandPropertiesGroup;
import com.cheejee.goodscenter.service.BrandPropertiesGroupService;
import com.cheejee.goodscenter.service.exception.DataNotExistException;
import com.cheejee.goodscenter.service.exception.DuplicateException;
import com.cheejee.goodscenter.validated.Check;
import com.cheejee.goodscenter.validated.InsertGroup;
import com.cheejee.goodscenter.validated.UpdateGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * @author CARRY
 * @Date 2020年10月23日上午11:20:18
 */
@Service
public class BrandPropertiesGroupSerivceImpl implements BrandPropertiesGroupService {
	@Resource
	private BrandPropertiesGroupMapper bpgMapper;
	
	@Resource
	private BrandPropertiesTemplateMapper bptMapper;

	@Override
	public Page<BrandPropertiesGroup> queryBrandPropertiesGroup(Integer brandId, String groupName, int pageNum, int pageSize) {
		return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> bpgMapper.seleteBySelective(brandId, groupName));
	}

	@Override
	public BrandPropertiesGroup queryBrandPropertiesGroupById(Integer id) {

		return bpgMapper.selectByPrimaryKey(id);
	}

	@Override
	@Check(group = InsertGroup.class, message = "新增的品牌属性分组不能为空")
	public int addBrandPropertiesGroup(BrandPropertiesGroup group) {

		if (!CollectionUtil.isEmpty(bpgMapper.seleteBySelective(null, group.getGroupName()))) {
			throw new DuplicateException("新增的品牌属性分组名称重复");
		}
		
		return bpgMapper.insertSelective(group);
	}

	@Override
	@Check(group = UpdateGroup.class, message = "修改的品牌属性分组不能为空")
	public int changeBrandPropertiesGroup(BrandPropertiesGroup group) {
		checkExist(group.getId());
		List<BrandPropertiesGroup> b = bpgMapper.seleteBySelective(null, group.getGroupName());

		if (!CollectionUtil.isEmpty(b) && b.get(0)
				.getId() != group.getId()) {
			throw new DuplicateException("修改的品牌属性分组名称重复");
		}

		return bpgMapper.updateByPrimaryKeySelective(group);
	}

	@Transactional
	@Override
	public int deleteBrandPropertiesGroup(Integer... id) {
		bptMapper.freedom(id);
		
		return bpgMapper.deleteById(id);
	}
	
	private void checkExist(Integer id) {
		if(bpgMapper.selectByPrimaryKey(id) == null) {
			throw new DataNotExistException("品牌属性分组不存在");
		}
	}

}
